package com.aizhixin.lab.statistics.controller;

import com.aizhixin.lab.account.dto.AccountDTO;
import com.aizhixin.lab.account.service.AccountService;
import com.aizhixin.lab.common.core.ApiReturnConstants;
import com.aizhixin.lab.common.utils.TokenUtil;
import com.aizhixin.lab.company.entity.Classes;
import com.aizhixin.lab.company.service.ClassesService;
import com.aizhixin.lab.config.Config;
import com.aizhixin.lab.course.course.entity.Course;
import com.aizhixin.lab.course.course.service.CourseService;
import com.aizhixin.lab.project.course.data.GroupResultData;
import com.aizhixin.lab.project.course.domain.KeyValueDomain;
import com.aizhixin.lab.project.course.domain.StuTaskListDomain;
import com.aizhixin.lab.statistics.domain.*;
import com.aizhixin.lab.statistics.service.TeacherDataService;
import com.aizhixin.lab.task.domain.ClassGradeDomain;
import io.swagger.annotations.*;
import org.apache.poi.hssf.usermodel.*;
import org.apache.poi.ss.util.CellRangeAddress;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletResponse;
import java.io.*;
import java.net.URLEncoder;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@RestController
@RequestMapping("/api/v1/statistics")
@Api(value = "老师数据Api", description = "老师数据统计")
public class TeacherDataController {
    @Autowired
    private AccountService accountService;
    @Autowired
    private TeacherDataService teacherDataService;
    @Autowired
    private ClassesService classesService;
    @Autowired
    private CourseService courseService;
    @Autowired
    private  Config config;
    @RequestMapping(value = "/getTeacherData", method = RequestMethod.GET, produces = MediaType.APPLICATION_JSON_VALUE)
    @ApiOperation(httpMethod = "GET", value = "教师总体数据统计", response = Void.class, notes = "教师总体数据统计<br>@author lwq")
    public ResponseEntity<?> teacherData(@RequestHeader("Authorization") String token) {
        AccountDTO account = accountService.getUserByToken(token);
        if (account == null) {
            return new ResponseEntity<Object>(TokenUtil.tokenValid(), HttpStatus.UNAUTHORIZED);
        }
        TeacherDataDomain dataDomain = teacherDataService.teacherData(account.getId());
        return new ResponseEntity(dataDomain, HttpStatus.OK);
    }

    @RequestMapping(value = "/getClassData", method = RequestMethod.GET, produces = MediaType.APPLICATION_JSON_VALUE)
    @ApiOperation(httpMethod = "GET", value = "班级数据统计", response = Void.class, notes = "班级数据统计<br>@author lwq")
    public ResponseEntity<?> getClassData(@RequestHeader("Authorization") String token) {
        AccountDTO account = accountService.getUserByToken(token);
        if (account == null) {
            return new ResponseEntity<Object>(TokenUtil.tokenValid(), HttpStatus.UNAUTHORIZED);
        }
        List<ClassDataDomain> classData = teacherDataService.getClassData(account.getId());
        return new ResponseEntity(classData, HttpStatus.OK);
    }

    @RequestMapping(value = "/getClassInfoData", method = RequestMethod.GET, produces = MediaType.APPLICATION_JSON_VALUE)
    @ApiOperation(httpMethod = "GET", value = "班级活跃度统计", response = Void.class, notes = "班级活跃度统计<br>@author lwq")
    public ResponseEntity<?> getClassInfoData(@RequestHeader("Authorization") String token,
                                              @ApiParam(value = "classId", required = true) @RequestParam(value = "classId") Long classId,
                                              @ApiParam(value = "day", required = true) @RequestParam(value = "day") Integer day) {
        AccountDTO account = accountService.getUserByToken(token);
        if (account == null) {
            return new ResponseEntity<Object>(TokenUtil.tokenValid(), HttpStatus.UNAUTHORIZED);
        }
        ClassDataInfoDomain classInfoData = teacherDataService.getClassInfoData(classId, day);
        return new ResponseEntity(classInfoData, HttpStatus.OK);
    }

    @RequestMapping(value = "/getClassLoginNum", method = RequestMethod.GET, produces = MediaType.APPLICATION_JSON_VALUE)
    @ApiOperation(httpMethod = "GET", value = "班级登陆次数", response = Void.class, notes = "班级登陆次数<br>@author lwq")
    public ResponseEntity<?> getClassLoginNum(@RequestHeader("Authorization") String token,
                                              @ApiParam(value = "classId", required = true) @RequestParam(value = "classId") Long classId,
                                              @ApiParam(value = "day", required = true) @RequestParam(value = "day") Integer day) {
        AccountDTO account = accountService.getUserByToken(token);
        if (account == null) {
            return new ResponseEntity<Object>(TokenUtil.tokenValid(), HttpStatus.UNAUTHORIZED);
        }
        LoginNumDomain classLoginNum = teacherDataService.getClassLoginNum(classId, day);
        return new ResponseEntity(classLoginNum, HttpStatus.OK);
    }
    @RequestMapping(value = "/getLoginNum", method = RequestMethod.GET, produces = MediaType.APPLICATION_JSON_VALUE)
    @ApiOperation(httpMethod = "GET", value = "班级日登陆次数", response = Void.class, notes = "班级登陆日次数<br>@author lwq")
    public ResponseEntity<?> getLoginNum(@RequestHeader("Authorization") String token,
                                              @ApiParam(value = "classId", required = true) @RequestParam(value = "classId") Long classId,
                                              @ApiParam(value = "day", required = true) @RequestParam(value = "day") Integer day) {
        AccountDTO account = accountService.getUserByToken(token);
        if (account == null) {
            return new ResponseEntity<Object>(TokenUtil.tokenValid(), HttpStatus.UNAUTHORIZED);
        }
        List<LoginDateNumDomain> loginNum = teacherDataService.getLoginNum(classId, day);
        return new ResponseEntity(loginNum, HttpStatus.OK);
    }

    @RequestMapping(value = "/getCourseData", method = RequestMethod.GET, produces = MediaType.APPLICATION_JSON_VALUE)
    @ApiOperation(httpMethod = "GET", value = "班级实验课数据", response = Void.class, notes = "班级实验课数据<br>@author lwq")
    public ResponseEntity<?> getCourseData(@RequestHeader("Authorization") String token,
                                           @ApiParam(value = "classId", required = true) @RequestParam(value = "classId") Long classId) {
        AccountDTO account = accountService.getUserByToken(token);
        if (account == null) {
            return new ResponseEntity<Object>(TokenUtil.tokenValid(), HttpStatus.UNAUTHORIZED);
        }
        ReturnDomain<TeacherCourseDomain> listReturnDomain = new ReturnDomain<>();
        Classes aClass = classesService.findClass(classId);
        List<TeacherCourseDomain> courseData = teacherDataService.getCourseData(account.getId(), classId);
        listReturnDomain.setName(aClass.getName());
        listReturnDomain.setData(courseData);
        return new ResponseEntity(listReturnDomain, HttpStatus.OK);
    }

    @RequestMapping(value = "/getChapterReport", method = RequestMethod.GET, produces = MediaType.APPLICATION_JSON_VALUE)
    @ApiOperation(httpMethod = "GET", value = "实验报告提交情况统计", response = Void.class, notes = "实验报告提交情况统计<br>@author lwq")
    public ResponseEntity<?> getChapterReport(@RequestHeader("Authorization") String token,
                                              @ApiParam(value = "courseId", required = true) @RequestParam(value = "courseId") String courseId,
                                              @ApiParam(value = "classId", required = true) @RequestParam(value = "classId") Long classId) {
        AccountDTO account = accountService.getUserByToken(token);
        if (account == null) {
            return new ResponseEntity<Object>(TokenUtil.tokenValid(), HttpStatus.UNAUTHORIZED);
        }

        List<ChapterReportDomain> chapterReport = teacherDataService.getChapterReport(courseId,classId);
        ReturnDomain<ChapterReportDomain> listReturnDomain = new ReturnDomain<>();
        Course course = courseService.findById(courseId);
        listReturnDomain.setName(course.getName());
        listReturnDomain.setData(chapterReport);
        return new ResponseEntity(listReturnDomain, HttpStatus.OK);
    }

    @RequestMapping(value = "/getChapterTaskScore", method = RequestMethod.GET, produces = MediaType.APPLICATION_JSON_VALUE)
    @ApiOperation(httpMethod = "GET", value = "实验报告成绩统计", response = Void.class, notes = "实验报告成绩统计<br>@author lwq")
    public ResponseEntity<?> getChapterTaskScore(@RequestHeader("Authorization") String token,
                                                 @ApiParam(value = "courseId", required = true) @RequestParam(value = "courseId") String courseId,
                                                 @ApiParam(value = "classId", required = true) @RequestParam(value = "classId") Long classId) {
        AccountDTO account = accountService.getUserByToken(token);
        if (account == null) {
            return new ResponseEntity<Object>(TokenUtil.tokenValid(), HttpStatus.UNAUTHORIZED);
        }
        List<ChapterReportDomain> reportScore = teacherDataService.getReportScore(courseId,classId);
        ReturnDomain<ChapterReportDomain> listReturnDomain = new ReturnDomain<>();
        Course course = courseService.findById(courseId);
        listReturnDomain.setName(course.getName());
        listReturnDomain.setData(reportScore);

        return new ResponseEntity(listReturnDomain, HttpStatus.OK);
    }

    @RequestMapping(value = "/getChapterTaskCommitNum", method = RequestMethod.GET, produces = MediaType.APPLICATION_JSON_VALUE)
    @ApiOperation(httpMethod = "GET", value = "课程任务提交统计", response = Void.class, notes = "课程任务提交统计<br>@author lwq")
    public ResponseEntity<?> getChapterTaskCommitNum(@RequestHeader("Authorization") String token,
                                                     @ApiParam(value = "courseId", required = true) @RequestParam(value = "courseId") String courseId,
                                                     @ApiParam(value = "classId", required = true) @RequestParam(value = "classId") Long classId) {
        AccountDTO account = accountService.getUserByToken(token);
        if (account == null) {
            return new ResponseEntity<Object>(TokenUtil.tokenValid(), HttpStatus.UNAUTHORIZED);
        }
        List<ChapterReportDomain> reportScore = teacherDataService.getChapterTaskCommitNum(courseId,classId);
        ReturnDomain<ChapterReportDomain> listReturnDomain = new ReturnDomain<>();
        Course course = courseService.findById(courseId);
        listReturnDomain.setName(course.getName());
        listReturnDomain.setData(reportScore);

        return new ResponseEntity(listReturnDomain, HttpStatus.OK);
    }

    @RequestMapping(value = "/getChapterTaskAvgScore", method = RequestMethod.GET, produces = MediaType.APPLICATION_JSON_VALUE)
    @ApiOperation(httpMethod = "GET", value = "课程成绩统计", response = Void.class, notes = "课程成绩统计<br>@author lwq")
    public ResponseEntity<?> getChapterTaskAvgScore(@RequestHeader("Authorization") String token,
                                                    @ApiParam(value = "courseId", required = true) @RequestParam(value = "courseId") String courseId,
                                                    @ApiParam(value = "classId", required = true) @RequestParam(value = "classId") Long classId) {
        AccountDTO account = accountService.getUserByToken(token);
        if (account == null) {
            return new ResponseEntity<Object>(TokenUtil.tokenValid(), HttpStatus.UNAUTHORIZED);
        }
        List<ChapterReportDomain> reportScore = teacherDataService.getChapterTaskAvgScore(courseId,classId);
        ReturnDomain<ChapterReportDomain> listReturnDomain = new ReturnDomain<>();
        Course course = courseService.findById(courseId);
        listReturnDomain.setName(course.getName());
        listReturnDomain.setData(reportScore);

        return new ResponseEntity(listReturnDomain, HttpStatus.OK);
    }

    @RequestMapping(value = "/getExperimentList", method = RequestMethod.GET, produces = MediaType.APPLICATION_JSON_VALUE)
    @ApiOperation(httpMethod = "GET", value = "教师端实验列表页", response = Void.class, notes = "教师端实验列表页<br>@author lwq")
    public ResponseEntity<?> ChapterReportDataDomain(@RequestHeader("Authorization") String token,
                                                     @ApiParam(value = "courseId", required = true) @RequestParam(value = "courseId") String courseId,
                                                     @ApiParam(value = "classId", required = true) @RequestParam(value = "classId") Long classId) {
        AccountDTO account = accountService.getUserByToken(token);
        if (account == null) {
            return new ResponseEntity<Object>(TokenUtil.tokenValid(), HttpStatus.UNAUTHORIZED);
        }
        List<ChapterReportDataDomain> domains = teacherDataService.ChapterReportDataDomain(courseId,classId);
        ReturnDomain<ChapterReportDataDomain> listReturnDomain = new ReturnDomain<>();
        Course course = courseService.findById(courseId);
        listReturnDomain.setName(course.getName());
        listReturnDomain.setData(domains);

        return new ResponseEntity(listReturnDomain, HttpStatus.OK);
    }

    @RequestMapping(value = "/getTaskList", method = RequestMethod.GET, produces = MediaType.APPLICATION_JSON_VALUE)
    @ApiOperation(httpMethod = "GET", value = "教师端任务列表页", response = Void.class, notes = "教师端任务列表页<br>@author lwq")
    public ResponseEntity<?> ChapterTaskDataDomain(@RequestHeader("Authorization") String token,
                                                   @ApiParam(value = "courseId", required = true) @RequestParam(value = "courseId") String courseId,
                                                   @ApiParam(value = "classId", required = true) @RequestParam(value = "classId") Long classId ) {
        AccountDTO account = accountService.getUserByToken(token);
        if (account == null) {
            return new ResponseEntity<Object>(TokenUtil.tokenValid(), HttpStatus.UNAUTHORIZED);
        }
        List<TaskDataDomain> taskDataDomains = teacherDataService.ChapterTaskDataDomain(courseId, classId);
        ReturnDomain<TaskDataDomain> listReturnDomain = new ReturnDomain<>();
        Course course = courseService.findById(courseId);
        listReturnDomain.setName(course.getName());
        listReturnDomain.setData(taskDataDomains);

        return new ResponseEntity(listReturnDomain, HttpStatus.OK);
    }

    @RequestMapping(value = "/lookFileType", method = RequestMethod.POST, produces = MediaType.APPLICATION_JSON_VALUE)
    @ApiOperation(httpMethod = "POST", value = "查看课程所有资源", response = Void.class, notes = "查看课程所有资源<br>@author lwq")
    @ApiResponses({@ApiResponse(code = 200, message = "OK", response = StuLookFileTypeDomain.class)})
    public ResponseEntity<?> lookFileType(@RequestHeader("Authorization") String token,
                                                     @RequestBody QueryStuLookFileDomain domain ) {
        AccountDTO account = accountService.getUserByToken(token);
        if (account == null) {
            return new ResponseEntity<Object>(TokenUtil.tokenValid(), HttpStatus.UNAUTHORIZED);
        }
        Map<String, Object> map = teacherDataService.lookFileTypeDomains(domain);


        return new ResponseEntity(map, HttpStatus.OK);
    }
    @RequestMapping(value = "/fileLook", method = RequestMethod.POST, produces = MediaType.APPLICATION_JSON_VALUE)
    @ApiOperation(httpMethod = "POST", value = "查看学生点击数及为点击的学生姓名", response = Void.class, notes = "查看学生点击数及为点击的学生姓名<br>@author lwq")
    @ApiResponses({@ApiResponse(code = 200, message = "OK", response = FileStuLookNumDomain.class)})
    public ResponseEntity<?> fileLook(@RequestHeader("Authorization") String token,
                                                     @RequestBody QueryStuLookFileDomain domain ) {
        AccountDTO account = accountService.getUserByToken(token);
        if (account == null) {
            return new ResponseEntity<Object>(TokenUtil.tokenValid(), HttpStatus.UNAUTHORIZED);
        }
        Map<String, Object> map = teacherDataService.fileLook(domain);


        return new ResponseEntity(map, HttpStatus.OK);
    }
    @RequestMapping(value = "/exportFileLook", method = RequestMethod.POST, produces = MediaType.APPLICATION_JSON_VALUE)
    @ApiOperation(httpMethod = "POST", value = "查看学生点击数及为点击的学生姓名", response = Void.class, notes = "查看学生点击数及为点击的学生姓名<br>@author lwq")
    @ApiResponses({@ApiResponse(code = 200, message = "OK", response = FileStuLookNumDomain.class)})
    public ResponseEntity<?> exportFileLook(@RequestHeader("Authorization") String token,
                                            @RequestBody QueryStuLookFileDomain domain, HttpServletResponse response ) throws IOException {
        AccountDTO account = accountService.getUserByToken(token);
        if (account == null) {
            return new ResponseEntity<Object>(TokenUtil.tokenValid(), HttpStatus.UNAUTHORIZED);
        }
        HSSFWorkbook wb = new HSSFWorkbook();
        HSSFSheet sheet = wb.createSheet("vid");
        domain.setPageSize(1000);
        Map<String, Object> map = teacherDataService.fileLook(domain);
        List<FileStuLookNumDomain> fileStuLookNumDomainList = (List<FileStuLookNumDomain>) map.get(ApiReturnConstants.DATA);
        int j=0;
        HSSFRow row = sheet.createRow(j );
        row.createCell(1).setCellValue("文件名");
        row.createCell(2).setCellValue("查看数");
        row.createCell(3).setCellValue("未看数");
        row.createCell(4).setCellValue("未查看的学生姓名");
        for (FileStuLookNumDomain f:fileStuLookNumDomainList){
            j++;
            HSSFRow row1 = sheet.createRow(j);
            row1.createCell(1).setCellValue(f.getName());
            row1.createCell(2).setCellValue(f.getLookNum());
            row1.createCell(3).setCellValue(f.getUnLookNum());
            StringBuffer stringBuffer = new StringBuffer();
            for (int i = 0; i < f.getStuName().size(); i++) {
                stringBuffer.append(f.getStuName().get(i));
                if (i > f.getStuName().size() - 1) {
                    stringBuffer.append(",");
                }
            }
            row1.createCell(4).setCellValue(stringBuffer.toString());
        }
        FileOutputStream output = new FileOutputStream(config.getBaseDir() + "/vid.xls");
        wb.write(output);
        output.flush();
        String basePath = config.getBaseDir() + "/vid.xls";
        File file = new File(basePath);
        // 取得文件名。
        String filename = file.getName().toString();

        // 取得文件的后缀名。
        String ext = filename.substring(filename.lastIndexOf(".") + 1).toUpperCase();

        // 以流的形式下载文件。
        InputStream fis = new BufferedInputStream(new FileInputStream(basePath));
        byte[] buffer = new byte[fis.available()];
        fis.read(buffer);
        fis.close();
        // 清空response
        response.reset();
        // 设置response的Header
        response.addHeader("Content-Disposition", "attachment;filename=" + URLEncoder.encode(System.currentTimeMillis() + ".xls", "UTF-8"));
        response.addHeader("Content-Length", "" + file.length());
        OutputStream toClient = new BufferedOutputStream(response.getOutputStream());
        response.setContentType("application/octet-stream");
        toClient.write(buffer);
        toClient.flush();
        toClient.close();
        return new ResponseEntity(map, HttpStatus.OK);
    }
    @RequestMapping(value = "/exportLookFileType", method = RequestMethod.POST, produces = MediaType.APPLICATION_JSON_VALUE)
    @ApiOperation(httpMethod = "POST", value = "导出课程所有资源查看数", response = Void.class, notes = "导出课程所有资源查看数<br>@author lwq")
    @ApiResponses({@ApiResponse(code = 200, message = "OK", response = StuLookFileTypeDomain.class)})
    public ResponseEntity<?> lookFileType(@RequestHeader("Authorization") String token,
                                          @RequestBody QueryStuLookFileDomain domain, HttpServletResponse response ) throws IOException {
        AccountDTO account = accountService.getUserByToken(token);
        if (account == null) {
            return new ResponseEntity<Object>(TokenUtil.tokenValid(), HttpStatus.UNAUTHORIZED);
        }
//        Map<String, Object> map = teacherDataService.lookFileTypeDomains(domain);
        HSSFWorkbook wb = new HSSFWorkbook();
        HSSFSheet sheet = wb.createSheet("vid");
        domain.setPageSize(1000);
        Map<String, Object> map = teacherDataService.lookFileTypeDomains(domain);
        List<StuLookFileTypeDomain> fileStuLookNumDomainList = (List<StuLookFileTypeDomain>) map.get(ApiReturnConstants.DATA);
        int j=0;
        HSSFRow row = sheet.createRow(j );
        row.createCell(1).setCellValue("学生姓名");
        row.createCell(2).setCellValue("PPT");
        row.createCell(3).setCellValue("视频");
        row.createCell(4).setCellValue("任务手册");
        row.createCell(5).setCellValue("任务指导手册");
        row.createCell(6).setCellValue("其他");
        for (StuLookFileTypeDomain f:fileStuLookNumDomainList){
            j++;
            HSSFRow row1 = sheet.createRow(j);
            row1.createCell(1).setCellValue(f.getName());
            row1.createCell(2).setCellValue(f.getPpt());
            row1.createCell(3).setCellValue(f.getVideo());
            row1.createCell(4).setCellValue(f.getTask());
            row1.createCell(5).setCellValue(f.getTask1());
            row1.createCell(6).setCellValue(f.getOther());

        }
        FileOutputStream output = new FileOutputStream(config.getBaseDir() + "/vid.xls");
        wb.write(output);
        output.flush();
        String basePath = config.getBaseDir() + "/vid.xls";
        File file = new File(basePath);
        // 取得文件名。
        String filename = file.getName().toString();

        // 取得文件的后缀名。
        String ext = filename.substring(filename.lastIndexOf(".") + 1).toUpperCase();

        // 以流的形式下载文件。
        InputStream fis = new BufferedInputStream(new FileInputStream(basePath));
        byte[] buffer = new byte[fis.available()];
        fis.read(buffer);
        fis.close();
        // 清空response
        response.reset();
        // 设置response的Header
        response.addHeader("Content-Disposition", "attachment;filename=" + URLEncoder.encode(System.currentTimeMillis() + ".xls", "UTF-8"));
        response.addHeader("Content-Length", "" + file.length());
        OutputStream toClient = new BufferedOutputStream(response.getOutputStream());
        response.setContentType("application/octet-stream");
        toClient.write(buffer);
        toClient.flush();
        toClient.close();
        return new ResponseEntity(map, HttpStatus.OK);
    }
    @RequestMapping(value = "/FileLookNum", method = RequestMethod.POST, produces = MediaType.APPLICATION_JSON_VALUE)
    @ApiOperation(httpMethod = "POST", value = "内容资源点击统计", response = Void.class, notes = "内容资源点击统计<br>@author lwq")
    @ApiResponses({@ApiResponse(code = 200, message = "OK", response = FileLookNumDomain.class)})
    public ResponseEntity<?> FileLookNum(@RequestHeader("Authorization") String token,
                                      @RequestBody QueryStuLookFileDomain domain ) {
        AccountDTO account = accountService.getUserByToken(token);
        if (account == null) {
            return new ResponseEntity<Object>(TokenUtil.tokenValid(), HttpStatus.UNAUTHORIZED);
        }
        List<FileLookNumDomain> fileLookNumDomains = teacherDataService.FileLookNum(domain);
        return new ResponseEntity(fileLookNumDomains, HttpStatus.OK);
    }
    @RequestMapping(value = "/getFileTotalNum", method = RequestMethod.GET, produces = MediaType.APPLICATION_JSON_VALUE)
    @ApiOperation(httpMethod = "GET", value = "获取章节文件总数", response = Void.class, notes = "获取章节文件总数<br>@author lwq")
    @ApiResponses({@ApiResponse(code = 200, message = "OK", response = FileNumDomain.class)})
    public ResponseEntity<?> getFileTotalNum(@RequestHeader("Authorization") String token,
                                             @RequestParam Long chapterId ) {
        AccountDTO account = accountService.getUserByToken(token);
        if (account == null) {
            return new ResponseEntity<Object>(TokenUtil.tokenValid(), HttpStatus.UNAUTHORIZED);
        }
        FileNumDomain fileTotalNum = teacherDataService.getFileTotalNum(chapterId);
        return new ResponseEntity(fileTotalNum, HttpStatus.OK);
    }
    @RequestMapping(value = "/getUnLookFile", method = RequestMethod.GET, produces = MediaType.APPLICATION_JSON_VALUE)
    @ApiOperation(httpMethod = "GET", value = "获取未查看的文件名", response = Void.class, notes = "获取未查看的文件名<br>@author lwq")
    @ApiResponses({@ApiResponse(code = 200, message = "OK", response = UnLookFileDomain.class)})
    public ResponseEntity<?> FileLookNum(@RequestHeader("Authorization") String token,
                                         @RequestParam Long chapterId,
                                         @RequestParam Long id) {
        AccountDTO account = accountService.getUserByToken(token);
        if (account == null) {
            return new ResponseEntity<Object>(TokenUtil.tokenValid(), HttpStatus.UNAUTHORIZED);
        }
        UnLookFileDomain unLookFile = teacherDataService.getUnLookFile(chapterId, id);
        return new ResponseEntity(unLookFile, HttpStatus.OK);
    }
    @RequestMapping(value = "/getStuLoginNum", method = RequestMethod.POST, produces = MediaType.APPLICATION_JSON_VALUE)
    @ApiOperation(httpMethod = "POST", value = "获取某日学生登录次数", response = Void.class, notes = "获取某日学生登录次数<br>@author lwq")
    @ApiResponses({@ApiResponse(code = 200, message = "OK", response = StuLoginNumDomain.class)})
    public ResponseEntity<?> getStuLoginNum(@RequestHeader("Authorization") String token,
                                        @RequestBody QueryStuLoginDomain domain) {
        AccountDTO account = accountService.getUserByToken(token);
        if (account == null) {
            return new ResponseEntity<Object>(TokenUtil.tokenValid(), HttpStatus.UNAUTHORIZED);
        }
        Map<String, Object> loginNum = teacherDataService.getLoginNum(domain);
        return new ResponseEntity(loginNum, HttpStatus.OK);
    }
    @RequestMapping(value = "/findEasyClassResult", method = RequestMethod.GET, produces = MediaType.APPLICATION_JSON_VALUE)
    @ApiOperation(value = "查看班级期末成绩(简单表)", httpMethod = "GET", notes = "查看班级期末成绩(简单表)")
    public ResponseEntity<?> findEasyClassResult(@RequestHeader("Authorization") String token, @RequestParam String courseId) {
        AccountDTO account = accountService.getUserByToken(token);
        Map<String, Object> result = new HashMap<String, Object>();
        if (account == null) {
            return new ResponseEntity<Object>(TokenUtil.tokenValid(), HttpStatus.UNAUTHORIZED);
        }
        List<ClassGradeDomain> classGradeDomainList = teacherDataService.courseResult(courseId, false);
        result.put(ApiReturnConstants.SUCCESS, true);
        result.put(ApiReturnConstants.DATA, classGradeDomainList);
        return new ResponseEntity(result, HttpStatus.OK);
    }
    @RequestMapping(value = "/exportEasyClassResult", method = RequestMethod.GET, produces = MediaType.APPLICATION_JSON_VALUE)
    @ApiOperation(value = "导出班级期末成绩(简单表)", httpMethod = "GET", notes = "导出班级期末成绩(简单表)")
    public ResponseEntity<?> exportEasyClassResult(@RequestHeader("Authorization") String token, @RequestParam String courseId, HttpServletResponse response) throws IOException {
        AccountDTO account = accountService.getUserByToken(token);
        Map<String, Object> result = new HashMap<String, Object>();
        if (account == null) {
            return new ResponseEntity<Object>(TokenUtil.tokenValid(), HttpStatus.UNAUTHORIZED);
        }
        List<ClassGradeDomain> classGradeDomainList = teacherDataService.courseResult(courseId, false);
        HSSFWorkbook wb = new HSSFWorkbook();
        HSSFSheet sheet = wb.createSheet("课程");
        for (int i=0;i<9;i++){
            sheet.autoSizeColumn(i);
        }
        HSSFRow row = sheet.createRow(0);
        row.createCell(0).setCellValue("班级名称");
        row.createCell(1).setCellValue("学生名称");
        row.createCell(2).setCellValue("考勤成绩");
        row.createCell(3).setCellValue("平时成绩");
        int i=1;
        for (ClassGradeDomain classGradeDomain : classGradeDomainList) {
            HSSFRow row1 = sheet.createRow(i);
            row1.createCell(0).setCellValue(classGradeDomain.getClassName());
            row1.createCell(1).setCellValue(classGradeDomain.getUserName());
            row1.createCell(2).setCellValue(classGradeDomain.getSignGrade());
            row1.createCell(3).setCellValue(classGradeDomain.getTaskGrade());
            i++;
        }
        FileOutputStream output = new FileOutputStream(config.getBaseDir() + "/aa.xls");
        wb.write(output);
        output.flush();
        String basePath = config.getBaseDir() + "/aa.xls";
        File file = new File(basePath);
        // 取得文件名。
        String filename = file.getName().toString();

        // 取得文件的后缀名。
        String ext = filename.substring(filename.lastIndexOf(".") + 1).toUpperCase();

        // 以流的形式下载文件。
        InputStream fis = new BufferedInputStream(new FileInputStream(basePath));
        byte[] buffer = new byte[fis.available()];
        fis.read(buffer);
        fis.close();
        // 清空response
        response.reset();
        // 设置response的Header
        response.addHeader("Content-Disposition", "attachment;filename=" + URLEncoder.encode(System.currentTimeMillis() + ".xls", "UTF-8"));
        response.addHeader("Content-Length", "" + file.length());
        OutputStream toClient = new BufferedOutputStream(response.getOutputStream());
        response.setContentType("application/octet-stream");
        toClient.write(buffer);
        toClient.flush();
        toClient.close();

        result.put(ApiReturnConstants.SUCCESS, true);
        result.put(ApiReturnConstants.DATA, classGradeDomainList);
        return new ResponseEntity(result, HttpStatus.OK);
    }
    @RequestMapping(value = "/findComplexClassResult", method = RequestMethod.GET, produces = MediaType.APPLICATION_JSON_VALUE)
    @ApiOperation(value = "查看班级期末成绩(复杂表)", httpMethod = "GET", notes = "查看班级期末成绩(复杂表)")
    public ResponseEntity<?> findComplexClassResult(@RequestHeader("Authorization") String token, @RequestParam String courseId) {
        AccountDTO account = accountService.getUserByToken(token);
        Map<String, Object> result = new HashMap<String, Object>();
        if (account == null) {
            return new ResponseEntity<Object>(TokenUtil.tokenValid(), HttpStatus.UNAUTHORIZED);
        }
        List<ClassGradeDomain> classGradeDomainList = teacherDataService.courseResult(courseId, true);
        result.put(ApiReturnConstants.SUCCESS, true);
        result.put(ApiReturnConstants.DATA, classGradeDomainList);
        return new ResponseEntity(result, HttpStatus.OK);
    }
    @RequestMapping(value = "/exportComplexClassResult", method = RequestMethod.GET, produces = MediaType.APPLICATION_JSON_VALUE)
    @ApiOperation(value = "导出班级期末成绩(复杂表)", httpMethod = "GET", notes = "导出班级期末成绩(复杂表)")
    public ResponseEntity<?> exportComplexClassResult(@RequestHeader("Authorization") String token, @RequestParam String courseId, HttpServletResponse response) throws IOException {
        AccountDTO account = accountService.getUserByToken(token);
        Map<String, Object> result = new HashMap<String, Object>();
        if (account == null) {
            return new ResponseEntity<Object>(TokenUtil.tokenValid(), HttpStatus.UNAUTHORIZED);
        }
        List<ClassGradeDomain> classGradeDomainList = teacherDataService.courseResult(courseId, true);
        HSSFWorkbook wb = new HSSFWorkbook();
        HSSFSheet sheet = wb.createSheet("课程");
        for (int i=0;i<9;i++){
            sheet.autoSizeColumn(i);
        }
        HSSFRow row = sheet.createRow(0);
        row.createCell(0).setCellValue("班级名称");
        row.createCell(1).setCellValue("学生名称");
        row.createCell(2).setCellValue("考勤成绩");
        row.createCell(3).setCellValue("平时成绩");
        row.createCell(4).setCellValue("任务名称");
        row.createCell(5).setCellValue("任务成绩");
        int i=1;
        int j=1;
        HSSFCellStyle cellStyle = wb.createCellStyle();
        cellStyle.setVerticalAlignment(HSSFCellStyle.VERTICAL_CENTER);
        for (ClassGradeDomain classGradeDomain : classGradeDomainList) {
           if ( classGradeDomain.getKeyValueDomains().size()>0) {
               CellRangeAddress callRangeAddress1 = new CellRangeAddress(i, i + classGradeDomain.getKeyValueDomains().size() - 1, 1, 1);//起始行,结束行,起始列,结束列
               sheet.addMergedRegion(callRangeAddress1);
               CellRangeAddress callRangeAddress2 = new CellRangeAddress(i, i + classGradeDomain.getKeyValueDomains().size() - 1, 2, 2);//起始行,结束行,起始列,结束列
               sheet.addMergedRegion(callRangeAddress2);
               CellRangeAddress callRangeAddress3 = new CellRangeAddress(i, i + classGradeDomain.getKeyValueDomains().size() - 1, 3, 3);//起始行,结束行,起始列,结束列
               sheet.addMergedRegion(callRangeAddress3);
               CellRangeAddress callRangeAddress4 = new CellRangeAddress(i, i + classGradeDomain.getKeyValueDomains().size() - 1, 0, 0);//起始行,结束行,起始列,结束列
               sheet.addMergedRegion(callRangeAddress4);
               for (KeyValueDomain keyValueDomain : classGradeDomain.getKeyValueDomains()) {
                   HSSFRow row2 = sheet.createRow(i);
//                   row1.createCell(0).setCellValue(classGradeDomain.getClassName());
//                   row1.createCell(1).setCellValue(classGradeDomain.getUserName());
//                   row1.createCell(2).setCellValue(classGradeDomain.getSignGrade());
//                   row1.createCell(3).setCellValue(classGradeDomain.getTaskGrade());
                   HSSFCell cell = row2.createCell(0);
                   cell.setCellValue(classGradeDomain.getClassName());
                   cell.setCellStyle(cellStyle);
                   HSSFCell cell2 = row2.createCell(1);
                   cell2.setCellValue(classGradeDomain.getUserName());
                   cell2.setCellStyle(cellStyle);
                   HSSFCell cell3 = row2.createCell(2);
                   cell3.setCellValue(classGradeDomain.getSignGrade());
                   cell3.setCellStyle(cellStyle);
                   HSSFCell cell4 = row2.createCell(3);
                   cell4.setCellValue(classGradeDomain.getTaskGrade());
                   cell4.setCellStyle(cellStyle);
                   row2.createCell(4).setCellValue(keyValueDomain.getKey());
                   row2.createCell(5).setCellValue(keyValueDomain.getValue());
                   i++;
               }
           }else {
               HSSFRow row2 = sheet.createRow(i);
               HSSFCell cell = row2.createCell(0);
               cell.setCellValue(classGradeDomain.getClassName());
               cell.setCellStyle(cellStyle);
               HSSFCell cell2 = row2.createCell(1);
               cell2.setCellValue(classGradeDomain.getUserName());
               cell2.setCellStyle(cellStyle);
               HSSFCell cell3 = row2.createCell(2);
               cell3.setCellValue(classGradeDomain.getSignGrade());
               cell3.setCellStyle(cellStyle);
               HSSFCell cell4 = row2.createCell(3);
               cell4.setCellValue(classGradeDomain.getTaskGrade());
               cell4.setCellStyle(cellStyle);
               i++;
           }

        }
        FileOutputStream output = new FileOutputStream(config.getBaseDir() + "/aa.xls");
        wb.write(output);
        output.flush();
        String basePath = config.getBaseDir() + "/aa.xls";
        File file = new File(basePath);
        // 取得文件名。
        String filename = file.getName().toString();

        // 取得文件的后缀名。
        String ext = filename.substring(filename.lastIndexOf(".") + 1).toUpperCase();

        // 以流的形式下载文件。
        InputStream fis = new BufferedInputStream(new FileInputStream(basePath));
        byte[] buffer = new byte[fis.available()];
        fis.read(buffer);
        fis.close();
        // 清空response
        response.reset();
        // 设置response的Header
        response.addHeader("Content-Disposition", "attachment;filename=" + URLEncoder.encode(System.currentTimeMillis() + ".xls", "UTF-8"));
        response.addHeader("Content-Length", "" + file.length());
        OutputStream toClient = new BufferedOutputStream(response.getOutputStream());
        response.setContentType("application/octet-stream");
        toClient.write(buffer);
        toClient.flush();
        toClient.close();

        result.put(ApiReturnConstants.SUCCESS, true);
        result.put(ApiReturnConstants.DATA, classGradeDomainList);
        return new ResponseEntity(result, HttpStatus.OK);
    }
}
